const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const courseController = require('../controllers/courses.controller.js');
const { verifyToken, isAdmin } = require('../middleware/auth.middleware.js');

// 配置视频上传
const videoStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../../public/uploads/videos'));
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
    cb(null, 'video-' + uniqueSuffix + path.extname(file.originalname));
  },
});
const videoUpload = multer({
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, 'public/uploads/videos');
    },
    filename: (req, file, cb) => {
      const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
      cb(null, 'video-' + uniqueSuffix + path.extname(file.originalname));
    },
  }),
  fileFilter: (req, file, cb) => {
    console.log('接收到的文件:', file); // 添加日志
    if (file.mimetype === 'video/mp4') {
      cb(null, true);
    } else {
      cb(new Error('只允许上传 MP4 格式的视频文件'));
    }
  },
});

router.get(
  '/with-registration',
  verifyToken,
  courseController.getCoursesWithRegistration
);
router.get('/', courseController.getAllCourses);
router.post('/', verifyToken, isAdmin, courseController.addCourse);
router.put('/:courseId', verifyToken, isAdmin, courseController.updateCourse);
router.delete(
  '/:courseId',
  verifyToken,
  isAdmin,
  courseController.deleteCourse
);
router.post('/enroll', verifyToken, courseController.enrollCourse);
router.post('/complete', verifyToken, courseController.completeCourse);
router.get('/user-courses', verifyToken, courseController.getUserCourses);

router.get('/:courseId', verifyToken, courseController.getCourseDetail);
router.post(
  '/:courseId/video',
  verifyToken,
  isAdmin,
  videoUpload.single('video'),
  courseController.uploadVideo
);
router.post('/:courseId/like', verifyToken, courseController.likeCourse);
router.post(
  '/:courseId/favorite',
  verifyToken,
  courseController.favoriteCourse
);

module.exports = router;
